#!/bin/bash
# This script is released under the GNU General Public License 3.0
# Check the COPYING file included with this distribution

# setprofile
# allows to choose a new profile in the DESTDIR env

# partition_finalise
# Creates filesystem, also with encryption, mounts the partitions
#
# parameters (required)
#  CONFIG_LIST: One string items of defined FSspec
#
# returns 0 on success
# returns $ERROR_CANCEL=64 on user cancel
# anything else is a real error
# reason: show_dialog() needs a way to exit "Cancel"
#
# writes menus and noise to STDERR

# location of other scripts to source
readonly SHAREDIR="$(dirname ${0})" || exit $?

# source common variables, functions and error handling
source "${SHAREDIR}"/common.sh || exit $?

#####################
## begin execution ##

# check input
check_num_args "$(basename $0)" 1 $# || exit $?
CONFIG_LIST="${1}"
RET_SUB=

# mount everything, including cryptsetup
"${SHAREDIR}"/FSspec mountall "${CONFIG_LIST}" || exit $?

chroot_mount || exit $?

OPTIONS=()
CUR_PROF_TYPE=""
CUR_PROF_NUM=""
CUR_PROF=
LINE=

CUR_PROF="$(chroot ${DESTDIR} eselect profile show | grep pentoo | awk '{match($1,"pentoo/.*",a)}END{print a[0]}')" || exit $?

if [[ -n "$(echo ${CUR_PROF} | grep hardened)" ]]; then
		CUR_PROF_TYPE="hardened"
elif [[ -n "$(echo ${CUR_PROF} | grep default)" ]]; then
		CUR_PROF_TYPE="default"
else
		show_dialog --keep-tite --msgbox "Warning: unable to detect a current Pentoo profile in the ${DESTDIR} directory" 0 0
fi

while read -r LINE; do
	#grab all pentoo profiles
	if [[ "${LINE}" == *pentoo* ]]; then
		#parse profiles based on the current type
		if [ "${CUR_PROF_TYPE}" == "hardened" ]; then
			PROF="$(echo "${LINE}" | awk '{match($2,"pentoo/hardened/.*",a)}END{print a[0]}')" || exit $?
		elif [ "${CUR_PROF_TYPE}" == "default" ]; then
			PROF="$(echo "${LINE}" | awk '{match($2,"pentoo/default/.*",a)}END{print a[0]}')" || exit $?
		fi
		#skip if the type is not current
		if [[ -z "${PROF}" ]]; then
			continue
		fi
		#detect its profile number
		PROF_NUM="$(echo "${LINE}" | awk '{match($1,"[0-9]+",a)}END{print a[0]}')" || exit $?
		#generate OPTIONS menu
		OPTIONS+=("${PROF_NUM}" "${PROF}") || exit $?
		#find current profile number
		if [[ "${PROF}" == "${CUR_PROF}" ]]; then
			CUR_PROF_NUM="${PROF_NUM}"
		fi
	fi
done < <(chroot "${DESTDIR}" eselect profile list) || exit $?

#check if any Pentoo profiles were found
if [ "${#OPTIONS[@]}" -eq 0 ]; then
	show_dialog --keep-tite --msgbox "ERROR: Unable to detect any Pentoo profile in the ${DESTDIR} directory" 0 0
	exit 1
fi

# ask for new profile
NEW_PROF_NUM="$(show_dialog --keep-tite --default-item "${CUR_PROF_NUM}" --menu "Select profile:" 0 0 16 "${OPTIONS[@]}")" || exit $?

# set new profile
chroot "${DESTDIR}" eselect profile set "${NEW_PROF_NUM}" || exit $?

chroot_umount || exit $?

exit 0
